Ext.apply(Ext.Msg, {

	error: function(text) {
		this.show({
			title: _('Error'),
			msg: text,
			buttons: this.OK,
			icon: this.ERROR 
		})
	},

	warn: function(text) {
		this.show({
			title: _('Notice'),
			msg: text,
			buttons: this.OK,
			icon: this.WARNING 
		})
	},
	
	message: function(text) {
		this.show({
			title: _('Verbum'),
			msg: text,
			buttons: this.OK
		})
	},

	info: function(text) {
		this.show({
			title: _('Notice'),
			msg: text,
			buttons: this.OK,
			icon: this.INFO 
		})
	}
         
});

function submitLogin(loginForm, loginWindow) {
	if (loginForm.getForm().isValid()) {
/*
		var util = new Verbum.Utilities();
		util.request({
			el: loginForm.getEl(),
			msg: _('Login in...'),
			warn: false,
			params: { 
			   action: 'login',
			   userid: loginForm.findById('userid').getValue(),
			   password: sha1Hash(loginForm.findById('password').getValue()),
			   rememberme: loginForm.findById('rememberme').getValue()
			  }											
		});
		
		util.on({
			'done': function(response) {
				obj = Ext.util.JSON.decode(response.responseText);
				window.location = obj.target;
				loginWindow.close();
			},
			'fail': function(response) {
				loginForm.getForm().reset();
				obj = Ext.util.JSON.decode(response.responseText); 
                Ext.Msg.alert(_('Login Failed!'), obj.errors.reason); 
			}
		})*/	

	    loginForm.getForm().submit({ 
	        method:'POST', 
	        waitTitle:_('Login in...'), 
	        waitMsg: _('Login in...'),
	 
			success:function(form, action){
				obj = Ext.util.JSON.decode(action.response.responseText);
				//window.location = obj.target;
				//loginWindow.close();
               loginForm.getForm().getEl().dom.method = 'POST';
               loginForm.getForm().getEl().dom.submit();
               loginWindow.close();				
			},
	       failure:function(form, action){ 
				loginForm.getForm().reset();
				if(action.failureType == 'server'){ 
					obj = Ext.util.JSON.decode(action.response.responseText); 
	                Ext.Msg.alert(_('Login Failed!'), obj.errors.reason); 
				    /*
				    loginForm.findById('userid').clearInvalid();
				    loginForm.findById('password').clearInvalid();
				    focus(loginForm,"userid");*/
	            }else{ 
	                Ext.Msg.alert(_('Warning!'), _('Authentication server is unreachable: ') + action.response.responseText); 
	            } 
	            //focus(loginForm,'userid');
	        } 
	    });
	}
}
function pressKey(field,e) {
	if (e.getKey() == Ext.EventObject.RETURN) {
		var frm = Ext.getCmp('loginForm');
		var win = Ext.getCmp('loginWindow');
		submitLogin(frm,win);
	}
}

function newAccountForm() {

    var TRecord = Ext.data.Record.create([
           {name: 'id', type: 'string'},
           {name: 'name', type: 'string'}
      ]);

	var ds = new Ext.data.Store({
		proxy: new Ext.data.HttpProxy({
			url: getMainUrl(),
			method: 'POST'
		}),
		baseParams: {action: 'system_list', op: 'team'},
		reader: new Ext.data.JsonReader({
			root: 'results'
		},TRecord)
	});

	ds.on({
		'load': {
			fn: function() {
				var t = new TRecord({
					id: 'ADMIN',
					name: _('Administrator')
				});
				ds.insert(0,t);
			}
		}
	});
	
	var bbar = new Ext.Toolbar({
		items:['->',
			{
				xtype:'button',
				tooltip: _('Cancel'),
				iconCls: 'cancel',
				text: _('Cancel'),
				handler: function() {
					win.close();
				}
			},
			{
				xtype:'button',
				tooltip: _('Send'),
				iconCls: 'send',
				text: _('Send'),
				handler: function() {
					if (form.getForm().isValid()) {
						if ("ADMIN"==form.findById('teamid_field').getValue()) {
							var util = new Verbum.Utilities();
							util.confirm(_('Did you verify that the desired team not exists before sending this message to the Administrator?'),
								function() {
				                    form.getForm().submit({ 
				                        method:'POST', 
				                        waitMsg: _('Please wait...'),
				 						
				                        success:function(form, action){
				                        	obj = Ext.util.JSON.decode(action.response.responseText);
				                        	Ext.Msg.message(obj.ret);
				                        	win.close();
				                        },
				 
				                        failure:function(form, action){ 
				                            if(action.failureType == 'server'){ 
				                                obj = Ext.util.JSON.decode(action.response.responseText); 
				                                Ext.Msg.error(obj.error); 
				                            }else{ 
				                                Ext.Msg.error(action.response.responseText); 
				                            } 
				                        } 
				                    });								
								});
						} else {
		                    form.getForm().submit({ 
		                        method:'POST', 
		                        waitMsg: _('Please wait...'),
		 						
		                        success:function(form, action){
		                        	obj = Ext.util.JSON.decode(action.response.responseText);
		                        	Ext.Msg.message(obj.ret);
		                        	win.close();
		                        },
		 
		                        failure:function(form, action){ 
		                            if(action.failureType == 'server'){ 
		                                obj = Ext.util.JSON.decode(action.response.responseText); 
		                                Ext.Msg.error(obj.error); 
		                            }else{ 
		                                Ext.Msg.error(action.response.responseText); 
		                            } 
		                        } 
		                    });								
						}
					}
				}
			}
		 ]		
	});
	
    form = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        //labelWidth: 70,
        url:getMainUrl(),
        baseParams: {action: 'message', op: 'ext'},
        defaultType: 'textfield',
        buttonAlign:'right',
        waitMsgTarget: true,
        bbar: bbar,
        autoWidth: true,
        autoHeight: true,
        defaults: {msgTarget:'side', allowBlank: false, anchor: '95%'},
        monitorResize: true,
        items: [{
            fieldLabel: _('e-mail'),
            name: 'email',
            id: 'email',
            vtype: 'email'
        },
        {
        	id: 'teamid_field',
			xtype: 'combo',
			fieldLabel: _('Team'),
			hiddenName: 'teamid',
			editable: false,
			allowBlank: false,
			forceSelection: true,
			triggerAction: 'all',
		   	store: ds,
		   	valueField: 'id',
		   	displayField: 'name',
		   	loadingText: _('Please wait...')
		   	//width: 170,
        }
        ,{
            hideLabel: true,
            name: 'message',
            xtype: 'textarea',
            selectOnFocus: true,
            height: 120
        },{
        	xtype: 'label',
        	html: _('Write your message above.<br/>The message will be sent to the team coordinator.<br/>It is also recommended to join the mailing list <u>opensuse-translation@opensuse.org</u>.<br/><b>If</b> the team you want to join <b>does not exists</b>, select Administrator.')
        }]
    });

    var win = new Ext.Window({
        title: _('Ask for a new account'),
        //autoWidth: true,
        width: 450,
        //height:260,
        minWidth: 450,
        minHeight: 250,
        layout: 'fit',
        bodyStyle:'padding:5px;',
        items: form,
		resizable: false,
		closable: false,
		draggable: true,
		modal: true
    });

    win.show();
    
	focus(form,'email');
	checkWidth(win);
    
}

function VerbumLogin() {

	Ext.QuickTips.init();
	
	var loginForm;
	
	var loginBbar = new Ext.Toolbar({
		items:[
			{
				xtype:'button',
				tooltip: _('Create new account'),
				text: _('Create new account'),
				handler: function() {
					newAccountForm();
				}
			},'->',
			{
				xtype:'button',
				tooltip: _('forgot password?'),
				text: _('forgot password?'),
				handler: function() {
					loginForm.findById('password').disable();
					if (loginForm.getForm().isValid()) {
       					loginForm.findById('password').setValue(" ");
	                    loginForm.getForm().submit({ 
	                        method:'POST', 
	                        waitMsg: _('Please wait...'),
	 						params: {op: 'rp'},
	 						
	                        success:function(form, action){
	                        	obj = Ext.util.JSON.decode(action.response.responseText);
	                        	Ext.Msg.message(obj.ret);
	                        	loginForm.getForm().reset();
	                        },
	 
	                        failure:function(form, action){ 
	                            loginForm.getForm().reset(); 
	                            if(action.failureType == 'server'){ 
	                                obj = Ext.util.JSON.decode(action.response.responseText); 
	                                Ext.Msg.error(obj.error); 
	                            }else{ 
	                                Ext.Msg.alert(_('Warning!'), _('Authentication server is unreachable: ') + action.response.responseText); 
	                            } 
	                        } 
	                    });	

					} else {
						Ext.Msg.info(_('Enter your username and click this button again. A new password will be sent to the registered e-mail address.'));
						focus(loginForm,'userid');
					}
					loginForm.findById('password').enable();
				}
			},
			{
				xtype:'button',
				tooltip: _('Login'),
				text: _('Login'),
				iconCls: 'login_button',
				handler: function() {
					submitLogin(loginForm,loginWindow);
				}
			}
		 ]		
	});
	
    loginForm = new Ext.FormPanel({
    /*
            onSubmit: Ext.emptyFn,
        submit: function() {
            loginForm.getForm().getEl().dom.submit();
        },
    */
    	id: 'loginForm',
        url:getMainUrl(),
		bodyStyle:'padding:5px 5px 0',
        baseCls: 'x-plain',
        //defaults: {width: 250},
        autoHeight: true,
        baseParams: {action: 'login'},
        defaultType: 'textfield',
        buttonAlign:'right',
        waitMsgTarget: true,
        bbar: loginBbar,
       	//labelWidth: 120,
        defaults: {msgTarget:'side', allowBlank: false, anchor: '90%', enableKeyEvents: true, listeners: {keypress: pressKey}}, 
        items: [{
            fieldLabel: _('Username'),
            name: 'userid',
            id: 'userid',
            blankText: _('Please, enter a valid Username.'),
            autoCreate:{tag: "input", type: "text", size: "20", autocomplete: "on"}
        },{
            fieldLabel: _('Password'),
            name: 'password',
            id: 'password',
            inputType: 'password',
            blankText: _('Please, enter a valid Password.'),
            autoCreate:{tag: "input", type: "password", size: "20", autocomplete: "on"}
        },{
        	xtype: 'checkbox',
        	hideLabel: true,
            boxLabel: _('Remember me'),
            name: 'rememberme',
            id: 'rememberme'
        }]
    });

    var loginWindow = new Ext.Window({
        title: _('Login'),
        //autoWidth: true,
        width: 400,
        //height:150,
        //minWidth: 320,
        //minHeight: 150,
        layout: 'fit',
        bodyStyle:'padding:5px;',
        items: loginForm,
		resizable: false,
		closable: false,
		draggable: false,
		id: 'loginWindow',
        iconCls: 'login'
    });
	
    loginWindow.show();
    
    //checkWidth(loginWindow);
    focus(loginForm,"userid");
    loginForm.findById('userid').clearInvalid();
    loginForm.findById('password').clearInvalid();

    if(window.console && window.console.firebug){
        Ext.Msg.warn(_('Firebug is known to cause performance issues.'));
    }
  
    /*
   	loginForm.render('login-form');
    
    */
};

Ext.onReady(VerbumLogin());

/*Ext.onReady(function(){
   Ext.QuickTips.init();

   // turn on validation errors beside the field globally
   Ext.form.Field.prototype.msgTarget = 'side';

   var simple = new Ext.form.FormPanel({
      standardSubmit:true,
      method: 'post',
      id: 'suscribe',
      renderTo: 'form1',
      labelWidth: 100,
      frame:true,
      border: false,
      width: 400,

      items: [
         {xtype:'fieldset',
            title: 'My title',
            collapsible: false,
            autoHeight:true,
            defaults: {width: 210, autoCreate:{tag: "input", type: "text", size: "20", autocomplete: "on"}},
            defaultType: 'textfield',
            width: 354,
            items :[{fieldLabel: 'label1',name: 'field2',allowBlank:false,maxLength: 100,itemCls: 'required'},
               {fieldLabel: 'label2',name: 'field2',allowBlank:false,maxLength: 200,itemCls: 'required'},
            ]
         },
         {xtype:'panel',
            width: 354,
            buttonAlign:'center',
            buttons:[{
               text: 'Etape suivante...',
               handler: function(){
                  if(simple.getForm().isValid()){
                     simple.getForm().getEl().dom.action = 'submitUrl';
                     simple.getForm().getEl().dom.method = 'POST';
                     simple.getForm().submit();
                  }
               }
            }]
         }
      ]
   });
});*/